<?php
/* 篇章管理相关操作控制器 */

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Storage;

class ExhibitOneController extends HomeController
{
    public function __construct(Request $request)
    {
        parent::__construct('get_exhibit_list');
    }
    //列表
    public function list(Request $request)
    {
        try {
            // 分页参数
            $page = $request->input('page', 1);
            $limit = $request->input('limit', 10);
            $name = $request->input('name');

            $condition = [];
            if ($name) {
                $condition[] = ['name', 'like', '%' . $name . '%'];
            }

            // 查询数据表
            $data = DB::table('exhibit_one')->where($condition)->orderBy('sort', 'asc')->offset(($page - 1) * $limit)->limit($limit)->get()->toArray();
            // 统计总记录数
            $count = DB::table('exhibit_one')->count();

            return response()->json([
                'code' => HTTP_OK,
                'message' => HTTP_OK_MESSAGE,
                'data' => $data,
                'count' => $count,
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取篇章列表失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取篇章列表失败',
                'data' => null
            ]);
        }
    }

    //不分页查询列表，供下拉选择框使用
    public function no_page_list(Request $request)
    {
        try {
            $field = ['id', 'name'];
            // 查询数据表
            $data = DB::table('exhibit_one')->select($field)->orderBy('sort', 'asc')->get()->toArray();

            return response()->json([
                'code' => HTTP_OK,
                'message' => HTTP_OK_MESSAGE,
                'data' => $data,
            ]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取篇章列表失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取篇章列表失败',
                'data' => null
            ]);
        }
    }

    //添加
    public function insert(Request $request)
    {
        try {
            $content = $request->input('content');
            $brief = $request->input('brief');
            if (!$content || $content == '<p><br></p>') {
                $content = '';
                //return response()->json(['code' => HTTP_ERROR,'message' => '内容不能为空']);
            }
            if (!$brief || $brief == '<p><br></p>') {
                $brief = '';
            }

            //接受参数并组装成数组
            $data = [];

            $data['name'] = $request->input('name');
            $data['english_name'] = $request->input('english_name') ? : '';
            $data['brief'] = $brief;
            $data['content'] = $content;
            $data['sort'] = $request->input('sort');
            $data['add_id'] = $this->user_id;

            //添加到数据表
            $id = DB::table('exhibit_one')->insertGetId($data);

            //处理文件
            $img_url = $request->input('img_url');
            if ($img_url) {
                foreach (explode(',', trim($img_url, ',')) as $key => $value) {
                    $item = [];
                    $item['exhibit_id'] = $id;
                    $item['level'] = 1;
                    $item['type'] = 1;
                    $item['url'] = $value;
                    $item['add_id'] = $this->user_id;
                    //添加数据到数据表
                    DB::table('exhibit_item')->insert($item);
                }
            }
            if ($request->input('audio_url')) {
                $item = [];
                $item['exhibit_id'] = $id;
                $item['level'] = 1;
                $item['type'] = 2;
                $item['url'] = $request->input('audio_url');
                $item['add_id'] = $this->user_id;
                //添加数据到数据表
                DB::table('exhibit_item')->insert($item);
            }

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('添加篇章失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '添加篇章失败',
                'data' => null
            ]);
        }
    }

    //删除
    public function delete(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');

            //查询有没有子分类
            $exists = DB::table('exhibit_two')->where('one_id', $id)->exists();
            if ($exists) {
                return response()->json(['code' => HTTP_ERROR,'message' => '存在下级展项，不能删除！']);
            }

            //删除数据
            DB::table('exhibit_one')->where('id', $id)->delete();

            //根据id查询多媒体文件,删除level为1的
            $item = DB::table('exhibit_item')->select('url')->where('level', 1)->where('exhibit_id', $id)->get()->toArray();
            $item = array_column($item, 'url');
            
            //同步删除多媒体文件
            Storage::delete($item);
            DB::table('exhibit_item')->where('level', 1)->where('exhibit_id', $id)->delete();

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('删除篇章失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '删除篇章失败',
                'data' => null
            ]);
        }
    }


    //修改
    public function update(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');
            $content = $request->input('content');
            $brief = $request->input('brief');
            if (!$content || $content == '<p><br></p>') {
                $content = '';
                //return response()->json(['code' => HTTP_ERROR,'message' => '内容不能为空']);
            }
            if (!$brief || $brief == '<p><br></p>') {
                $brief = '';
            }

            //接受参数并组装成数组
            $data = [];
            $data['name'] = $request->input('name');
            $data['english_name'] = $request->input('english_name') ? : '';
            $data['brief'] = $brief;
            $data['content'] = $content;
            $data['sort'] = $request->input('sort');

            //添加到数据表
            DB::table('exhibit_one')->where('id', $id)->update($data);
            
            //处理文件
            $img_url = $request->input('img_url');
            if ($img_url) {
                foreach (explode(',', trim($img_url, ',')) as $key => $value) {
                    //根据id查询多媒体文件是否存在
                    $exists = DB::table('exhibit_item')->where('url', $value)->where('level', 1)->where('exhibit_id', $id)->exists();
                    //存在不用处理，不存在的添加
                    if (!$exists) {
                        $item = [];
                        $item['exhibit_id'] = $id;
                        $item['level'] = 1;
                        $item['type'] = 1;
                        $item['url'] = $value;
                        $item['add_id'] = $this->user_id;
                        //添加数据到数据表
                        DB::table('exhibit_item')->insert($item);
                    }
                }
            }
            $audio_url = $request->input('audio_url');
            if ($audio_url) {
                //根据id查询多媒体文件是否存在
                $exists = DB::table('exhibit_item')->where('url', $audio_url)->where('level', 1)->where('exhibit_id', $id)->exists();
                if (!$exists) {
                    //添加数据到数据表
                    $item = [];
                    $item['exhibit_id'] = $id;
                    $item['level'] = 1;
                    $item['type'] = 2;
                    $item['url'] = $audio_url;
                    $item['add_id'] = $this->user_id;
                    //添加数据到数据表
                    DB::table('exhibit_item')->insert($item);
                }
            }

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('修改篇章失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '修改篇章失败',
                'data' => null
            ]);
        }
    }

    //删除多媒体文件
    public function delete_item(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');
            $path = $request->input('path');
            //删除数据
            DB::table('exhibit_item')->where('id', $id)->delete();

            //同步删除多媒体文件
            Storage::delete($path);

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('删除多媒体文件失败: ' . $e->getMessage());
        }
    }

    //详情
    public function detail(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');
            //根据id查询详情
            $data = DB::table('exhibit_one')->where('id', $id)->first();

            //根据id查询多媒体文件
            $item = DB::table('exhibit_item')->select('id', 'type', 'url')->where('level', 1)->where('exhibit_id', $id)->orderBy('id','asc')->get()->toArray();
            foreach ($item as $key => $value) {
                $item[$key]->path = $value->url;
                $item[$key]->url = Storage::url($value->url);
            }
            $data->item = $item;

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE,'data' => $data]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取篇章详情失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取篇章详情失败',
                'data' => null
            ]);
        }
    }


    //提供给小程序的接口，查询各级展项列表
    public function get_exhibit_list(Request $request)
    {
        try {
            //接受参数
            $id = $request->input('id');
            //根据id查询详情
            $one = DB::table('exhibit_one')->orderBy('sort','asc')->get()->toArray();
            $two = DB::table('exhibit_two')->orderBy('sort','asc')->get()->toArray();
            $three = DB::table('exhibit_three')->orderBy('sort','asc')->get()->toArray();


            $field = ['id', 'exhibit_id', 'type', 'url'];
            //查询多媒体文件
            $one_item = DB::table('exhibit_item')->select($field)->where('level', 1)->orderBy('id','asc')->get()->toArray();
            $two_item = DB::table('exhibit_item')->select($field)->where('level', 2)->orderBy('id','asc')->get()->toArray();
            $three_item = DB::table('exhibit_item')->select($field)->where('level', 3)->orderBy('id','asc')->get()->toArray();


            //遍历数据把多媒体文件添加到各自的展项上
            foreach ($one as $key => $value) {
                $one[$key]->item = [];
                foreach ($one_item as $k => $v) {
                    if ($one[$key]->id == $v->exhibit_id) {
                        $v->url = Storage::url($v->url);
                        $one[$key]->item[] = $v;
                    }
                }
            }
            $new_two = [];
            foreach ($two as $key => $value) {
                $two[$key]->item = [];
                foreach ($two_item as $k => $v) {
                    if ($two[$key]->id == $v->exhibit_id) {
                        $v->url = Storage::url($v->url);
                        $two[$key]->item[] = $v;
                    }
                }
                //改成以one_id为键的数组
                $new_two[$value->one_id][] = $two[$key];
            }
            $new_three = [];
            foreach ($three as $key => $value) {
                $three[$key]->item = [];
                foreach ($three_item as $k => $v) {
                    if ($three[$key]->id == $v->exhibit_id) {
                        $v->url = Storage::url($v->url);
                        $three[$key]->item[] = $v;
                    }
                }
                //改成以two_id为键的数组  
                $new_three[$value->two_id][] = $three[$key];
            }


            //遍历数据把子级分别添加到各自的父级上
            foreach ($one as $key => $value) {
                $one[$key]->children = [];
                foreach ($two as $k => $v) {
                    $two[$k]->children = [];
                    //先把第三级添加到第二级上
                    foreach ($three as $m => $n) {
                        if ($two[$k]->id == $n->two_id) {
                            $two[$k]->children[] = $n;
                        }
                    }
                    //再把第二级添加到一级上
                    if ($one[$key]->id == $v->one_id) {
                        $one[$key]->children[] = $two[$k];
                    }
                }
            }

            
            $data = [];
            $data['one'] = $one;
            $data['two'] = $new_two;
            $data['three'] = $new_three;

            return response()->json(['code' => HTTP_OK,'message' => HTTP_OK_MESSAGE,'data' => $data]);
        } catch (\Exception $e) {
            // 记录错误日志
            Log::error('获取展项列表失败: ' . $e->getMessage());
            return response()->json([
                'code' => HTTP_ERROR,
                'message' => '获取展项列表失败',
                'data' => null
            ]);
        }
    }

}
